package com.april.pattern.creational.singleton;

import java.io.Serializable;

/**
 * @author April
 * @version V1.0.0
 * @date 2019/06/23 09:20
 * @description 饿汉式
 */
public class HungrySingleton implements Serializable {
    public static final HungrySingleton HUNGRY_SINGLETON;

    static {
        HUNGRY_SINGLETON = new HungrySingleton();
    }

    private HungrySingleton() {
        // 反射防御的代码
        // 对于饿汉式和静态内部类式这种是有效的，其它的方式是无法避免反射攻击的
        if (HUNGRY_SINGLETON != null) {
            throw new RuntimeException("禁止使用反射破坏单例!");
        }
    }

    public static HungrySingleton getInstance() {
        return HUNGRY_SINGLETON;
    }

    /**
     * 解决读写序列化破坏单例
     * 必须是这个名字，详见ObjectStream的L524
     *
     * @return HungrySingleton
     */
    private Object readResolve() {
        return HUNGRY_SINGLETON;
    }
}
